package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;



import pojo.Book;
import pojo.Record;
import pojo.User;
import service.BookManager;
import service.BookManagerImpl;
import service.UserManager;
import service.UserManagerImpl;
import sun.security.util.Password;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Logger logger = Logger.getLogger(this.getClass());
		String uname = request.getParameter("uname");
		String password = request.getParameter("pswd");
		User su = new User(null, uname, password);
		UserManager um = new UserManagerImpl();
		User user = um.findUser(su);
		if(user!=null){
			request.getSession().setAttribute("user", user);
			BookManager bm = new BookManagerImpl();
			List<Book> booklist = bm.loadAllBooks();
			request.getSession().setAttribute("booklist", booklist);
			List<Record> records = new ArrayList<Record>();
			for(Book b : booklist){
				records.add(new Record(null, user.getUid(), b.getBid(), 0, null));
			}
			request.getSession().setAttribute("records", records);
			response.sendRedirect("shopping");
			logger.info(uname+"登陆了，时间");
		}
		else{
			response.sendRedirect("login.jsp");
		}
	}

}
